export function uuid() {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  var uuid = s.join('')
  return uuid
}

export function renderTime(date) {
  if (date) {
    var dateee = new Date(date).toJSON()
    return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
  } else {
    return ''
  }
}


export function getTime() {
  Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
      'M+': this.getMonth() + 1, // 月份
      'd+': this.getDate(), // 日
      'h+': this.getHours(), // 小时
      'm+': this.getMinutes(), // 分
      's+': this.getSeconds(), // 秒
      'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
      'S': this.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)) }
    for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
    return fmt
  }
  return new Date().Format('yyyy-MM-dd hh:mm:ss')
}

// 转时间戳
export function getDateTimeStamp(dateStr) {
  return Date.parse(dateStr.replace(/-/gi, '/'))
}

// 转换为几天前
export function getDateDiff(dateTimeStamp) {
  var result
  var minute = 1000 * 60
  var hour = minute * 60
  var day = hour * 24
  var halfamonth = day * 15
  var month = day * 30
  var year = day * 365
  var now = new Date().getTime()
  var diffValue = now - dateTimeStamp
  if (diffValue < 0) { return }
  var yearC = diffValue / year
  var monthC = diffValue / month
  var weekC = diffValue / (7 * day)
  var dayC = diffValue / day
  var hourC = diffValue / hour
  var minC = diffValue / minute
  if (yearC >= 1) {
    result = '' + parseInt(yearC) + '年前'
  }
  if (monthC >= 1) {
    result = '' + parseInt(monthC) + '月前'
  } else if (weekC >= 1) {
    result = '' + parseInt(weekC) + '周前'
  } else if (dayC >= 1) {
    result = '' + parseInt(dayC) + '天前'
  } else if (hourC >= 1) {
    result = '' + parseInt(hourC) + '小时前'
  } else if (minC >= 1) {
    result = '' + parseInt(minC) + '分钟前'
  } else { result = '刚刚' }
  return result
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 *
 */
export function formatRichText(html) {
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
    return match
  })
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')
    return match
  })
  newContent = newContent.replace(/<br[^>]*\/>/gi, '')
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"')
  return newContent
}


///将富文本编辑器的img的src提取
export function findImgtags1(detail) {
  let contentImg = []
  detail.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, function (match, capture) {
    contentImg.push(capture);
  });
  return contentImg
}

// 将上传后的图片替换出路径
export function replaceTxt(detail, replaceArrUrl) {
  var contentImg = [];
  detail.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, function (match, capture) {
    contentImg.push(capture);
  });
  if (contentImg.length > 0) {
    //开始替换图片url
    for (var i = 0; i < contentImg.length; i++) {
      detail = detail.replace(contentImg[i], replaceArrUrl[i])

    }
  }
  return detail
}


// 计算年龄
export function jsGetAge(strBirthday) { //传入形式yyyy-MM-dd
  //strBirthday = util.formatTime(strBirthday);转换成yyyy-MM-dd形式
  if (!strBirthday) {
    return 0;
  }
  var returnAge
  var strBirthdayArr = strBirthday.split('-')
  var birthYear = strBirthdayArr[0]
  var birthMonth = strBirthdayArr[1]
  var birthDay = strBirthdayArr[2]
  var d = new Date()
  var nowYear = d.getFullYear()
  var nowMonth = d.getMonth() + 1
  var nowDay = d.getDate()
  if (nowYear == birthYear) {
    returnAge = 0 //同年 则为0岁
  } else {
    var ageDiff = nowYear - birthYear //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay //日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1
        } else {
          returnAge = ageDiff
        }
      } else {
        var monthDiff = nowMonth - birthMonth //月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1
        } else {
          returnAge = ageDiff
        }
      }
    } else {
      returnAge = -1 //返回-1 表示出生日期输入错误 晚于今天
    }
  }
  return returnAge //返回周岁年龄
}

//格式化为年月(去掉横岗2010-06)
export function renderTime3(date) {
  if (date) {
    var dateee = new Date(date).toJSON()
    let date1 = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    return date1.toString().slice(0, 11)
  } else {
    return ''
  }
}

//格式化为年月日()
export function renderTime2(date) {
  if (date) {
    var dateee = new Date(date).toJSON()
    let date1 = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    return date1.toString().substr(0, 10)
  } else {
    return ''
  }
}


// 参数秒 输出03:05:59  时分秒
export function secondToDate(result) {
  var h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
  var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
  var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
  return result = h + ":" + m + ":" + s;
}


//字符串按照英文字母顺序排序
export function getABC(str) {
  return str.split("").sort().join("");
}

/**
 * 数据 按照 拼音首字母 排序 并分组
 * 
 * @param {Array} data ; 需要 排序的 数据
 * @param {String} field ；必须；排序所依据的 字段 名
 * 
 * @return {Json} ; 例如：{A:[{},{}],B:[{},{}],C:[{}],#:[]}
 */
export const dataLetterSort = (data, field) => {
  var letter_reg = /^[A-Z]$/;
  var list = new Array();
  for (var i = 0; i < data.length; i++) {
    // 添加 # 分组，用来 存放 首字母不能 转为 大写英文的 数据
    // list['#'] = new Array();
    // 首字母 转 大写英文
    let letter = (data[i][field]).substr(0, 1).toUpperCase();
    // 是否 大写 英文 字母
    if (!letter_reg.test(letter)) {
      letter = '#';
    }
    // 创建 字母 分组
    if (!(letter in list)) {
      list[letter] = new Array();
    }
    // 字母 分组 添加 数据
    list[letter].push(data[i]);
  }
  // 转换 格式 进行 排序；
  var resault = new Array();
  for (var key in list) {
    resault.push({
      letter: key,
      list: list[key]
    });
  }
  resault.sort(function (x, y) {
    return x.letter.charCodeAt(0) - y.letter.charCodeAt(0);
  });
  // # 号分组 放最后
  var last_arr = resault[0];
  resault.splice(0, 1);
  resault.push(last_arr);

  // 转换 数据 格式
  var json_sort = {}
  for (var i = 0; i < resault.length; i++) {
    json_sort[resault[i].letter] = resault[i].list;
  }
  return list
}

//input数字转换金额千分位显示方法
const MoneyTest = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;

// 金额添加千分位
const comdify = function (n) {
  if (!n) return n;
  let str = n.split('.');
  let re = /\d{1,3}(?=(\d{3})+$)/g;
  let n1 = str[0].replace(re, "$&,");
  return str.length > 1 && str[1] ? `${n1}.${str[1]}` : `${n1}.00`;
};
//去除千分位中的‘，’
export const delcommafy = (num) => {
  if (!num) return num;
  num = num.toString();
  num = num.replace(/,/gi, '');
  return num;
};
const valdateFn = function (rule, val, cb) {
  setTimeout(() => {
    if (val) {
      let inputVal = delcommafy(val);
      if (rule.test(inputVal)) {
        cb()
      } else {
        cb('只能是数字金额,最多两位小数')
      }
    }
    cb()
  })
}
// 验证金额数字可以为负数
const moneyValid = function (rule, val, cb) {
  valdateFn(/((^-?[1-9]\d*)|^-?0)(\.\d{0,2}){0,1}$/, val, cb);
};
// 验证金额数字不可以为负数
const moneyNValid = function (rule, val, cb) {
  valdateFn(MoneyTest, val, cb);
};

// 获取输入框的值
export const getInputValue = (el) => {
  let inputVal = el || '';
  return comdify(delcommafy(inputVal));
};

